<?php
/**
 * @package		简易CMS
 * @subpackage	插件函数包
 * @version		$Id: option_focus.php 25 2012-08-29 17:55:19Z htmambo@gmail.com $
 * @author		Hoping
 * @copyright	Copyright (C) 2010 Hoping Software Studio.
 */

//保证此文件不被直接执行
defined ( 'IN_JYCMS' ) or die ( 'Direct Access to this location is not allowed.' );

define ( 'CURSCRIPT', 'focus' );

class focus_ctrl extends application {

	function __construct() {
		$this->focus_ctrl ();
	}

	function focus_ctrl() {
		$this->allowaction = array (
			'index', 'log',
			'update', 'engine', 'content', 'img',
			'testcontentrule', 'delcontentrule', 'contentrule',
			'testengine', 'delengine', 'modifyengine', 'setting',
			'new', 'modify', 'relation', 'addkeyword', 'keyword' );
		$this->cachelist = array ('portalcategory' );
		parent::__construct ();
		$needperm = array(
			'update', 'engine', 'content', 'img',
			'testcontentrule', 'delcontentrule', 'contentrule',
			'testengine', 'delengine', 'modifyengine', 'setting'
		);
		$needlogin = array('new', 'modify', 'relation', 'addkeyword', 'keyword');
		//判断权限
		if(in_array($_G['gp_task'], $needperm)){
			if(!checkperm('allowmanagearticle')){
				showmessage('You do not have permission to use the action!', dreferer());
			}
		}
		if(in_array($_G['gp_task'], $needlogin) && !$_G['uid']){
			showmessage('You do not have permission to use the action!', dreferer());
		}
	}
	function onindex() {
		global $_G;
		$navtitle = $this->lang->_('Keywords');
		$this->load ( 'function/portalcp' );
		$cattree = getcattree ();
		if (submitcheck ( 'search' )) {
			$keyword = $_G ['gp_keyword'];
			$created = $_G ['gp_created'];
			if ($keyword) {
				$where [] = "`name` LIKE '%$keyword%'";
			}
			if ($created) {
				if ($created == 1) {
					$where [] = "readtime=0";
				} elseif ($created == 2) {
					$sql [] = "readtime!=0";
					$where [] = "(" . implode ( " OR ", $sql ) . ")";
				}
			}
			if ($where) {
				$where = ' WHERE ' . implode ( ' AND ', $where );
			}
		}
		if (submitcheck ( 'submit' )) {
			if ($_G ['adminid'] == 1) {
				if ($newcatid = $_POST ['newcatid']) {
					$oldcatid = $_POST ['oldcatid'];
					foreach ( $newcatid as $k => $v ) {
						$v = intval ( $v );
						$ov = intval ( $oldcatid [$k] );
						if ($v == $ov) {
							unset ( $newcatid [$k] );
						} else {
							DB::update ( 'focus_keywords', array ('catid' => $v ), "id='$k'" );
						}
					}
					unset ( $_G ['gp_newcatid'], $_G ['gp_oldcatid'] );
				}
				if ($newenabled = $_G ['gp_newenabled']) {
					$oldenabled = $_G ['gp_oldenabled'];
					$ids = array();
					foreach ( $newenabled as $k => $v ) {
						$v = intval ( $v );
						$ov = intval ( $oldenabled [$k] );
						if ($v == $ov) {
							unset ( $newenabled [$k] );
						} else {
							$ids [] = $k;
						}
					}
					if ($ids) {
						$ids = implode ( ',', $ids );
						DB::update ( 'focus_keywords', array ('enabled' => '1-enabled' ), "id IN($ids)" );
					}
				}
				unset ( $_G ['gp_newenabled'], $_G ['gp_oldenabled'] );
				if ($newname = $_G ['gp_newname']) {
					$oldname = $_G ['gp_oldname'];
					foreach ( $newname as $k => $v ) {
						$v = trim ( $v );
						$v = focuscensor ( $v );
						if ($v && $v != $oldname [$k]) {
							$sql = "SELECT COUNT(*) FROM #__focus_keywords WHERE name='$v' AND id!='$k'";
							$result = DB::result_first ( $sql );
							if (! $result)
								DB::update ( 'focus_keywords', array ('name' => $v ), "id='$k'" );
						}
					}
					unset ( $_G ['gp_newname'], $_G ['gp_oldname'] );
				}
				if ($ids = $_G ['gp_ids']) {
					$ids = implode ( ',', $ids );
					DB::delete ( 'focus_keywords', "id IN($ids)" );
				}
			}
		}

		$kwlist = array ();
		$sql = "SELECT COUNT(*) FROM #__focus_keywords $where";
		$query = DB::query ( $sql );
		$count = DB::result ( $query );
		$page = max ( 1, intval ( $_G ['gp_page'] ) );
		$perpage = 15;
		if ($count) {
			list ( $start, $totalpage, $perpage ) = $this->page_get_start ( $page, $count, $perpage );
			$query = DB::query ( "SELECT * FROM #__focus_keywords $where ORDER BY dateline DESC LIMIT $start, $perpage" );
			while ( $value = DB::fetch_array ( $query ) ) {
				$value ['dateline'] = dgmdate ( $value ['dateline'] );
				$value ['canedit'] = true;
				$k = 'readtime';
				if ($value [$k]) {
					$value ['canedit'] = false;
					$value [$k] = dgmdate ( $value [$k] );
				} else {
					$value [$k] = lang ( 'focus', 'Not updated' );
				}
				$value ['isenabled'] = $value ['enabled'] ? lang ( 'core', 'Yes' ) : lang ( 'core', 'No' );
				$kwlist [] = $value;
			}
			$multi = multi ( $count, $perpage, $page, "index.php?option=focus" );
		}
		$taks = 'index';
		include template ( 'diy:focus/index' );
	}

	function onnew() {
		global $_G;
		if (! $_G ['uid']) {
			showmessage ( "Please login first!", 'index.php?option=focus' );
		}
		if (submitcheck ( 'submit' )) {
			if ($keywords = $_G ['gp_keywords']) {
				$ks = explode ( "\n", $keywords );
			}
			$newscatid = intval ( $_G ['gp_newscategory'] );
			$data = array ('dateline' => TIMESTAMP, 'uid' => $_G ['uid'], 'username' => $_G ['username'], 'catid' => $newscatid, 'enabled' => $_G ['isadmin'] );
			$num = $banned = $repeat = 0;
			foreach ( $ks as $v ) {
				$v = focuscensor ( $v );
				if (! $v) {
					$banned ++;
				} else {
					$sql = "SELECT * FROM #__focus_keywords WHERE `name`='$v'";
					$result = DB::result ( DB::query ( $sql ) );
					if ($result) {
						$repeat ++;
					} else {
						$num ++;
						$data ['name'] = $v;
						DB::insert ( 'focus_keywords', $data );
					}
				}
			}
			$msg = '';
			if ($banned) {
				$msg .= 'Filters {banned} illegal words,';
			}
			if ($repeat) {
				$msg .= 'Neglected {repeat} repetitions words,';
			}
			if (! $num) {
				showmessage ( 'Sorry, ' . $msg . 'You do not have to add new keywords!', 'index.php?option=focus', array ('banned' => $banned, 'repeat' => $repeat ) );
			}
			showmessage ( $msg . 'You have just added a total of {num} new key words!', 'index.php?option=focus', array ('banned' => $banned, 'repeat' => $repeat, 'num' => $num ) );
		} else {
			showmessage ( 'Your request origin is not correct, can not be submitted.', 'index.php?option=focus' );
		}
	}

	/**
	 * 采集记录
	 *
	 */
	function onlog() {
		global $_G;
		$navtitle = lang ( 'focus', 'System Log' );
		$keyword = trim ( $_GET ['keyword'] );
		if ($keyword) {
			$where [] = " `keyword` like '%" . $keyword . "%'";
			$urlpre .= "&keyword=$keyword";
		}
		$orderby = trim ( $_GET ['orderby'] );
		if (! $orderby)
			$orderby = "id";
		$ordermod = trim ( $_GET ['ordermod'] );
		$ozf = "&nbsp;&nbsp;[↑]";
		$opx = "desc";
		if ($ordermod != 'asc') {
			$ordermod = "desc";
			$ozf = "&nbsp;&nbsp;[↓]";
			$opx = "asc";
		}
		$urlpre .= "&orderby=$orderby&ordermod=$ordermod";

		$theurl = 'index.php?option=focus&task=log' . $urlpre;
		$orderid = "<a href='$theurl&orderby=id&ordermod=$opx'>ID</a>";
		$orderurl = "<a href='$theurl&orderby=nums&ordermod=$opx'>" . lang ( 'core', 'Number' ) . "</a>";
		$ordertime = "<a href='$theurl&orderby=dateline&ordermod=$opx'>" . lang ( 'core', 'DateTime' ) . "</a>";
		if ($orderby == 'id')
			$orderid .= $ozf;
		elseif ($orderby == 'dateline')
			$ordertime .= $ozf;
		else
			$orderurl .= $ozf;
		$order = " ORDER BY $orderby $ordermod";
		if ($where)
			$where = " WHERE " . implode ( " AND ", $where );
		$perpage = 10;
		$query = DB::query ( "SELECT COUNT(*) FROM #__focus_log $where" );
		$listcount = DB::result ( $query, 0 );
		$multipage = "";
		$listarr = array ();
		if ($listcount) {
			$start = ($_GET ['page'] - 1) * $perpage;
			if ($start < 0) {
				$_GET ['page'] = 1;
				$start = 0;
			}
			$query = "SELECT * FROM #__focus_log $where $order LIMIT " . $start . "," . $perpage;
			$query = DB::query ( $query );
			while ( $item = DB::fetch_array ( $query ) ) {
				if ($item ['note']) {
					$note = unserialize ( $item ['note'] );
					if ($note) {
						foreach ( $note as $k => $v ) {
							$v = str_replace ( '"', '', $v );
							$note [$k] = str_replace ( "'", '', $v );
						}
						$note = '<table class=datalist><tr><td>' . implode ( '</td></tr><tr><td>', $note ) . '</td></tr></table>';
						$note = '<a class="modal" onclick="showDialog(\'' . $note . '\', \'notice\');" href="javascript:void(0);" style="color:red"><u>' . lang ( 'core', 'View' ) . '</u></A>';
					} else {
						$note = '&nbsp;';
					}
				} else {
					$note = '&nbsp;';
				}
				$item ['note'] = $note;
				$listarr [] = $item;
			}
			$multipage = multi ( $listcount, $perpage, $_GET ['page'], $theurl );
		}
		include template ( 'diy:focus/log' );
	}

	/**
	 * 测试采集规则
	 *
	 */
	function ontestcontentrule() {
		global $_G;
		$id = intval ( $_G ['gp_id'] );
		if (! $id) {
			showmessage ( "Sorry, you do not specify the entry to the test!", 'index.php?option=focus&task=content' );
		}
		$query = DB::query ( "select * from #__focus_contentrule where id='$id'" );
		$row = DB::fetch_array ($query);
		if (! $row) {
			showmessage ( "Sorry, you do not specify the entry to the test!", 'index.php?option=focus&task=content' );
		}
		if (! $row ['replace'])
			$row ['replace'] = 'This is for test!';
		$this->load ( 'class/import' );
			DB::query ( "select count(*) as num from #__focus_urlhistory where url like ('%" . $row ['url'] . "%') order by id desc" );
			$count = DB::result ();
			if (! $count) {
				showmessage ( "Sorry, the system temporarily for testing do not address!", 'index.php?option=focus&task=content' );
			}
			DB::query ( "select * from #__focus_urlhistory where url like ('%" . $row ['url'] . "%') order by id desc" );
			$urls = DB::fetch_array ();
			if (! $urls) {
				showmessage ( "Sorry, the system temporarily for testing do not address!", 'index.php?option=focus&task=content' );
			}
			$row ['url'] = $urls ['url'];
			$row ['format'] = 'http';
			$im = new import ();


			$result = $im->geturl ( $row );
			$sourcehtml = $im->sourcehtml;
		$navtitle = lang ( 'focus', 'Test collection rules' );
		$infoarr = array ("code" => $result, "url" => $urls['url'], "rule" => $row ['rule'], "source" => $sourcehtml );
		//$navtitle = '系统中共有' . $count . '条记录与此规则匹配！';
		$html = printruledebug ( $infoarr );
		$this->showhtml ( $html );
	}

	/**
	 * 删除采集规则
	 *
	 */
	function ondelcontentrule() {
		global $_G;
		$id = intval ( $_G ['gp_id'] );
		if (! $id) {
			showmessage ( "Sorry, you do not specify to delete the entry!", 'index.php?option=focus&task=content' );
		}
		DB::query ( "delete from #__focus_contentrule where id='$id'" );
		loadcache( 'contentrule', 1 );
		showmessage ( "The specified entry has been deleted!", 'index.php?option=focus&task=content' );
	}

	/**
	 * 编辑、添加采集规则
	 *
	 */
	function oncontentrule() {
		global $_G;
		$id = intval ( $_G ['gp_id'] );
		if ($id) {
			$sql = "select * from #__focus_contentrule where id='$id'";
			$query = DB::query ( $sql );
			$row = DB::fetch_array ($query);
			if (! $row) {
				showmessage ( "Sorry, you specify the rules do not exist!", 'index.php?option=focus&task=content' );
			}
		}
		if ($_POST ['addnew'])
			unset ( $_POST );
		if (submitcheck ('savesubmit')) {
			unset ( $_POST ['savesubmit'], $_POST ['id'] );
			if ($id) {
				$sql = "update";
			} else {
				$url = $_POST ['url'];
				$sql = "select count(*) from #__focus_contentrule where url = '" . $url . "'";
				DB::query ( $sql );
				$result = DB::result ();
				if ($result) {
					showmessage ( "The rules you specify already exists!", 'index.php?option=focus&task=content' );
				}
				$sql = "insert into";
			}
			unset ( $_POST ['formhash'] );
			unset ( $_POST ['a'] );
			unset ( $_POST ['m'] );
			unset ( $_POST ['ids'] );
			unset ( $_POST ['sid'] );

			$sql .= " #__focus_contentrule set ";
			foreach ( $_POST as $k => $v ) {
				$sql .= "`$k` = '$v',";
			}
			$sql = substr ( $sql, 0, - 1 );
			if ($id)
				$sql .= " WHERE id='$id'";
			DB::query ( $sql );
			if (! $id)
				$id = DB::insert_id ();
			loadcache ( 'contentrule', 1 );
			showmessage ( "Operation has been completed! About to enter the test page!", 'index.php?option=focus&task=testcontentrule&id=' . $id );
		} else {
			$navtitle = '修改搜索引擎地址';
			include template('focus/content');
		}
	}

	/**
	 * 采集规则列表
	 *
	 */
	function oncontent() {
		global $_G;
		$navtitle = '采集规则';
		if (submitcheck ()) {
			if ($_POST ['ids']) {
				$ids = implode ( ",", $_POST ['ids'] );
				$sql = "delete from #__focus_contentrule where id in ($ids)";
				DB::query ( $sql );
				loadcache ( 'contentrule', 1 );
				showmessage ( "Specified search rules have been deleted!", 'index.php?option=focus&task=ontentrule' );
			} else {
				showmessage ( "Undefined operation and returns the list!", 'index.php?option=focus&task=ontentrule' );
			}
		} else {
			$urlpre = '';
			$keyword = trim ( $_G['gp_keyword'] );
			if ($keyword) {
				DB::query ( "select count(*) as num from #__focus_urlhistory where url like ('%" . $keyword . "%') order by id desc" );
				$count = DB::result ();
				$where [] = " url like '%" . $keyword . "%'";
				$urlpre .= "&keyword=$keyword";
			}
			$orderby = trim ( $_GET ['orderby'] );
			if (! $orderby)
				$orderby = "id";
			$ordermod = trim ( $_GET ['ordermod'] );
			$ozf = "&nbsp;&nbsp;[↑]";
			$opx = "desc";
			if ($ordermod != 'asc') {
				$ordermod = "desc";
				$ozf = "&nbsp;&nbsp;[↓]";
				$opx = "asc";
			}
			$urlpre .= "&orderby=$orderby&ordermod=$ordermod";

			$theurl = 'index.php?option=focus&task=content' . $urlpre;
			$orderid = "<a href='$theurl&orderby=id&ordermod=$opx'>ID</a>";
			$orderurl = "<a href='$theurl&orderby=url&ordermod=$opx'>URL</a>";

			if ($orderby == 'id')
				$orderid .= $ozf;
			else
				$orderurl .= $ozf;

			$order = " ORDER BY $orderby $ordermod";
			if ($where)
				$where = " WHERE " . implode ( " AND ", $where );
			$perpage = 15;
			$query = DB::query ( "SELECT COUNT(*) FROM #__focus_contentrule " . $where );
			$listcount = DB::result ( $query, 0 );
			$multipage = "";
			$listarr = array ();
			if ($listcount) {
				$start = ($_GET ['page'] - 1) * $perpage;
				if ($start < 0) {
					$_GET ['page'] = 1;
					$start = 0;
				}
				$query = "SELECT * FROM #__focus_contentrule $where $order LIMIT " . $start . "," . $perpage;
				$query = DB::query ( $query );
				while ( $item = DB::fetch_array ( $query ) ) {
					$listarr [] = $item;
				}
				$multipage = multi ( $listcount, $perpage, $_GET ['page'], $theurl );
			}
			include template ( 'diy:focus/content' );
		}
	}

	/**
	 * 测试搜索引擎设置
	 *
	 */
	function ontestengine() {
		global $_G;
		$id = intval ( $_G ['gp_id'] );
		if (! $id) {
			showmessage ( "Sorry, you do not specify to test the entry!", 'index.php?option=focus&task=engine' );
		}
		$query = DB::query ( "select * from #__focus_searchengine where id='$id'" );
		$row = DB::fetch_array ($query);
		$keyword = 'test';

		$row['url'] = str_replace ( "{keyword}", urlencode ( $keyword ), $row ['url'] );
		$row['url'] = str_replace ( "{number}", 20, $row ['url'] );
		list ( $result, $sourcehtml, $results ) = processurl ( $row );
		$infoarr = array ("code" => $result, "url" => $row ['url'], "rule" => $row ['rule'], "source" => $sourcehtml );
		$navtitle = '测试搜索引擎规则';
		$html = printruledebug ( $infoarr );
		$this->showhtml ( $html );
	}

	/**
	 * 删除搜索引擎规则
	 *
	 */
	function ondelengine() {
		global $_G;
		$id = intval ( $_G ['gp_id'] );
		if (! $id) {
			showmessage ( "Sorry, you do not specify to delete the entry!", 'index.php?option=focus&task=engine' );
		}
		DB::query ( "delete from #__focus_searchengine where id='$id'" );
		loadcache ( 'engine', 1 );
		showmessage ( "The specified entry has been deleted!", 'index.php?option=focus&task=engine' );
	}

	/**
	 * 编辑、添加搜索引擎
	 *
	 */
	function onmodifyengine() {
		global $_G;
		$id = intval ( $_G['gp_id'] );
		if ($id) {
			$sql = "select * from #__focus_searchengine where id='$id'";
			$query = DB::query ( $sql );
			$row = DB::fetch_array ( $query );
			if (! $row) {
				showmessage ( "Sorry, your search rules specified does not exist!", 'index.php?option=focus&task=engine' );
			}
		}
		if (submitcheck ('savesubmit')) {
			$va = array(
				'url', 'charset', 'format', 'titlehl', 'contenthl', 'replace', 'rule', 'fullcontent'
			);
			$data = array();
			foreach((array)$va as $v){
				$data[$v] = trim($_POST[$v]);
			}
			if ($id) {
				DB::update('focus_searchengine', $data, array('id'=>$id));
			} else {
				$id = DB::insert('focus_searchengine', $data, 1);
			}
			loadcache ( 'engine', 1 );
			showmessage ( "Operation has been completed! About to enter the test page!", 'index.php?option=focus&task=testengine&id=' . $id );
		} else {
			$navtitle = '修改搜索引擎地址';
			include template('focus/engine');
		}
	}

	/**
	 * 搜索引擎列表
	 *
	 */
	function onengine() {
		global $_G;
		if (submitcheck('savesubmit')) {
			if ($_G['gp_ids']) {
				$ids = implode ( ",", $_G['gp_ids'] );
				$sql = "delete from #__focus_searchengine where id in ($ids)";
				DB::query ( $sql );
				loadcache ( 'engine', 1 );
				showmessage ( "Specified search rules have been deleted!", 'index.php?option=focus&task=engine' );
			} else {
				showmessage ( "Undefined operation and returns the list!", 'index.php?option=focus&task=engine' );
			}
		} else {
			$navtitle = '搜索引擎列表';
			$perpage = 20;
			$query = DB::query ( "SELECT COUNT(*) FROM #__focus_searchengine " );
			$listcount = DB::result ( $query, 0 );
			$multipage = "";
			$listarr = array ();
			if ($listcount) {
				$order = "id DESC";
				$start = ($_GET ['page'] - 1) * $perpage;
				if ($start < 0) {
					$_GET ['page'] = 1;
					$start = 0;
				}
				$query = "SELECT * FROM #__focus_searchengine ORDER BY id desc LIMIT " . $start . "," . $perpage;
				$query = DB::query ( $query );
				while ( $item = DB::fetch_array ( $query ) ) {
					$listarr [] = $item;
				}
				$multipage = multi ( $listcount, $perpage, $_GET ['page'], $theurl . $urlplus );
			}
			include template ( 'diy:focus/engine' );
		}
	}

	/**
	 * 编辑关键字
	 *
	 */
	function onmodify() {
		global $_G;
		$id = intval ( $_G ['gp_id'] );
		if (! $id) {
			showmessage ( "Sorry, you do not select keywords!", 'index.php?option=focus&task=index' );
		}
		$sql = "select * from #__focus_keywords where id='$id'";
		DB::query ( $sql );
		$row = DB::fetch_array ();
		if (! $row) {
			showmessage ( "Sorry, you specify the keyword does not exist!", 'index.php?option=focus&task=index' );
		}
		if (submitcheck ()) {
			unset ( $_POST ['id'], $_POST ['savesubmit'], $_POST ['sid'] );
			unset ( $_POST ['formhash'] );
			$sql = "update #__focus_keywords set ";
			foreach ( $_POST as $k => $v ) {
				$sql .= $k . "='" . intval ( $v ) . "',";
			}
			$sql = substr ( $sql, 0, - 1 );
			$sql .= " WHERE id='$id'";
			DB::query ( $sql );
			showmessage ( "Keyword {keyword} in the information has been updated successfully!", 'index.php?option=focus&task=index' );
		} else {
			$navtitle = '关键字“' . $row ['name'] . '”聚合设置';
			$html .= label ( array ("type" => "form-start", "name" => "thevalueform", "action" => 'index.php?option=focus&task=modify' ) );
			$html .= label ( array ("type" => "div-start" ) );
			$html .= label ( array ("type" => "table-start" ) );
			$html .= '<tr><th><b>分类</b></th>';
				$catstr = '';
				$v1 = $v;
				$clistarr = $_ENV ['categories']->getcategory ( $v1 );
				foreach ( $clistarr as $key => $value ) {
					$catstr .= "<option value=\"" . $value ['catid'] . "\"";
					$vv = $v . "catid";
					if ($row [$vv] == $value ['catid'])
						$catstr .= " selected=true ";
					$catstr .= ">" . $value ['pre'] . $value ['name'] . "</option>";
				}
				$html .= "<td>";
				$html .= "<select id=\"" . $v . "catid\" name=\"" . $v . "catid\">\r\n\t\t<option value=\"0\">请选择分类</option>\r\n\t\t{$catstr}\r\n\t\t</select>";
				$html .= "</td></tr>";
			$html .= "<tr><th>&nbsp;</th><td>请选择关键字“" . $row ['name'] . "”所聚合的内容需要导入的相应分类</td></tr>";
			$html .= label ( array ("type" => "table-end" ) );
			$html .= label ( array ("type" => "div-end" ) );
			$html .= label ( array ("type" => "hidden", "name" => "id", "value" => $row ['id'] ) );
			$html .= "<input type=\"submit\" name=\"savesubmit\" value=\"提交\" class=\"btn\">\r\n\t\t<input type=\"reset\" name=\"importreset\" value=\"重置\" class=\"btn\">";
			$html .= label ( array ("type" => "form-end" ) );
			$this->showhtml ( $html );
		}
	}

	/**
	 * 读取相关词语
	 *
	 */
	function onrelation() {
		global $_G;
		$keyword = trim ( $_GET ['keyword'] );
		if (! $keyword)
			showmessage ( "Sorry, you do not specify the keyword!", 'index.php?option=focus&task=index' );
		$keyword_list = relation_keyword_list ( $keyword );
		if (! $keyword_list) {
			showmessage ( "{keyword} does not find relevant keywords!", 'index.php?option=focus&task=index', array ('keyword' => $keyword ) );
		}
		$navtitle = '与关键字“' . $keyword . '"”相关的词语';
		$html .= label ( array ("type" => "form-start", "name" => "thevalueform", "action" => 'index.php?option=focus&task=addkeyword&keyword=' . $keyword ) );
		$html .= label ( array ("type" => "div-start" ) );
		$html .= label ( array ("type" => "table-start" ) );
		$html .= '<tr>
			<td><input class="checkbox" type="checkbox" name="chkall" onclick="checkall(this.form,\'keywords\')" checked>全选
			&nbsp;&nbsp;共有' . count ( $keyword_list ) . '个与<b>' . $keyword . '</b>相关的关键字，请选择添加!</td></tr><tr></tr>';
		foreach ( $keyword_list as $v ) {
			$html .= '<tr><td><input class="checkbox" type="checkbox" name="keywords[]" value="' . $v . '" checked>
			<a href="http://index.baidu.com/main/word.php?word=' . urlencode ( $v ) . '" target="_blank" title="点此查看百度指数">' . $v . '</a></td></tr>';
		}
		$html .= label ( array ("type" => "table-end" ) );
		$html .= label ( array ("type" => "div-end" ) );
		$html .= label ( array ("type" => "hidden", "name" => "id", "value" => $row ['id'] ) );
		$html .= "<input type=\"submit\" name=\"savesubmit\" value=\"提交\" class=\"btn\">";
		$html .= label ( array ("type" => "form-end" ) );
		$this->showhtml ( $html );
	}

	/**
	 * 添加关键字
	 *
	 */
	function onaddkeyword() {
		global $_G;
		if (submitcheck () || $_GET ['id_count']) {
			if (isset ( $_FILES ['keywords_file'] )) {
				$keyword_list = file ( $_FILES ['keywords_file'] ['tmp_name'] );
			}
			$id_start = $id_end = null;
			if (is_numeric ( $_POST ['id_start'] ) || is_numeric ( $_GET ['id_start'] )) {
				$id_start = $_POST ['id_start'] ? $_POST ['id_start'] : $_GET ['id_start'];
			}
			if (is_numeric ( $_POST ['id_end'] ) || is_numeric ( $_GET ['id_end'] )) {
				$id_end = $_POST ['id_end'] ? $_POST ['id_end'] : $_GET ['id_end'];
			}
			if ($id_start && $id_end) {
				$id = intval ( $_GET ['id'] );
				//生成相关关键字
				if ($id_start > $id_end) {
					$id_start_tmp = $id_start;
					$id_start = $id_end;
					$id_end = $id_start_tmp;
				}
				if ($id > $id_end)
					showmessage ( "Related keyword completion", 'index.php?option=focus&task=index' );
				if ($id == 0)
					$id = $id_start;
				$sql = "select id,name,catid from #__focus_keywords where id>=$id and id<=$id_end limit 1";
				DB::Query ( $sql );
				$keyword_info = DB::fetch_array ();

				if (! $keyword_info)
					showmessage ( "Related keyword completion", null );
				$keyword_list = relation_keyword_list ( $keyword_info ['name'] );
				$next_id = $keyword_info ['id'] + 1;
				$id_count = $_GET ['id_count'] + 1;
				$next_url = sprintf ( "index.php?option=focus&task=addkeyword&id_start=%s&id_end=%s&id=%s&id_count=%s", $id_start, $id_end, $next_id, $id_count );
				$msg = "Start ID:{$id_start}&nbsp;&nbsp;&nbsp;&nbsp;End ID:{$id_end}<br><br>";
				$msg .= "Current ID:{$id}&nbsp;&nbsp;&nbsp;Current keyword:{$keyword_info['name']}<br><br>";
			}
			$keyword_list = $keyword_list ? $keyword_list : array ();
			if ($keywords = $_POST ['keywords']) {
				$keyword_list = array_merge ( $keyword_list, is_array ( $keywords ) ? $keywords : explode ( "\n", $keywords ) );
			}
			$keyword_list = array_unique ( $keyword_list );
			$timestamp = time ();
			$count = 0;
			foreach ( $keyword_list as $keyword ) {
				if ($keyword = trim ( $keyword )) {
					if ($illegal_msg = filter ( $keyword )) {
						$illegal_msg = lang ( 'focus', "And illegal Keywords" );
						continue;
					}
					if ($keyword_info) {
						$blogcatid = $newscatid = $imagecatid = $videocatid = 0;
						foreach ( $keyword_info as $k => $v ) {
							$$k = intval ( $v );
						}
					}
					$sql = "select id from #__focus_keywords where name='$keyword'";
					DB::query ( $sql );
					$row = DB::fetch_array ();
					if (! $row) {
						$sql = "insert into #__focus_keywords
					(name,catid,uid,username,dateline) values
					('$keyword','$catid','" . $_G ['uid'] . "','" . $_G ['username'] . "','" . time () . "')";
						$query = DB::Query ( $sql, "SKIP_ERROR" );
						$query && $count ++;
					}
				}
			}
			if ($next_url) {
				$to = $next_url;
			} else {
				$to = 'index.php?option=focus&task=index';
			}
			showmessage ( "{msg}Filter out duplicate names (illegal_msg) after successfully added {count} keywords.", $to, array ('$illegal_msg' => $illegal_msg, 'count' => $count, 'msg' => $msg ) );
		}
		showmessage ( "The operation has been completed to add keywords!", 'index.php?option=focus&task=index' );
	}

	/**
	 * 关键字列表
	 *
	 */
	function onkeyword() {
		global $_G;
		$navtitle = '关键字列表';
		if (submitcheck () || $_G ['gp_code']) {
			unset ( $_POST ['chkall'] );
			if (! $_POST ['code'])
				unset ( $_POST ['ids'] );
			$namenew = &$_POST ['namenew'];
			$nameold = &$_POST ['nameold'];
			$code = $_G ['gp_code'];
			$ids = $_POST ['ids'];
			$id = $_G ['gp_id'];
			if ($code == 'del') {
				if (! $ids)
					$ids = array ($id );
				foreach ( $ids as $v ) {
					unset ( $namenew [$v] );
					unset ( $nameold [$v] );
				}
				if (! $namenew) {
					unset ( $namenew, $nameold, $_POST ['namenew'], $_POST ['nameold'] );
				}
				$ids = implode ( ",", $ids );
				$sql = "delete from #__focus_keywords where id in($ids)";
				DB::query ( $sql );
			}
				$var = 'catid';
				if (is_array ( $this->post [$var] ) && count ( $this->post [$var] )) {
					foreach ( $this->post [$var] as $key => $vv ) {
						$v1 = $var . '_old';
						if ($vv && $vv != $this->post [$v1] [$key]) {
							$sql = "UPDATE #__focus_keywords set $var = '$vv' WHERE id='$key'";
							DB::query ( $sql );
						}
					}
				}
			if ($namenew) {
				$upids = array ();
				foreach ( $namenew as $k => $v ) {
					if ($v !== $nameold [$k])
						$upids [$k] = $v;
				}
				if ($upids) {
					foreach ( $upids as $k => $v ) {
						//如果新名字重名，将不会被更新
						$sql = "select id from #__focus_keywords where name='$v'";
						DB::query ( $sql );
						$row = DB::fetch_array ();
						if (! $row) {
							$sql = "update #__focus_keywords set name='" . $v . "' where id='$k'";
							DB::query ( $sql );
						}
					}
				}
				if ($code == 'update') {
					$ids = implode ( ",", $ids );
					$url = "index.php?option=focus&task=update&ids=$ids";
					showmessage ( "The system will start to be updated!", $url );
				}
				unset ( $namenew, $nameold, $_POST ['namenew'], $_POST ['nameold'] );
			}
			showmessage ( "Batch operations have been completed!", 'index.php?option=focus&task=index' );
		} else {
			$created = intval ( $_GET ['created'] );
			if ($created == 1) {
				$where [] = "readtime=0";
			} elseif ($created == 2) {
				$sql [] = "readtime!=0";
				$where [] = "(" . implode ( " OR ", $sql ) . ")";
			}
			$urlplus = "&created=" . $created;
			$keyword = trim ( $_GET ['keyword'] );
			if ($keyword) {
				$urlplus .= "&keyword=" . urlencode ( $keyword );
				$where [] = " name like '%$keyword%'";
			}
			if ($where) {
				$wheresqlstr = " WHERE " . implode ( " AND ", $where );
			}
			$theurl = 'index.php?option=focus&task=index';
			$perpage = 20;
			$query = DB::query ( "SELECT COUNT(*) FROM #__focus_keywords " . $wheresqlstr );
			$listcount = DB::result ( $query, 0 );
			$multipage = "";

			$listarr = array ();
			if ($listcount) {
				if (empty ( $_GET ['order'] )) {
					$order = "id DESC, dateline DESC";
				} else {
					$order = $_GET ['order'] . " " . $_GET ['sc'];
				}
				$start = ($_GET ['page'] - 1) * $perpage;
				if ($start < 0) {
					$_GET ['page'] = 1;
					$start = 0;
				}
				//加载分类缓存，如果没有设置，则重建分类索引
				loadcache ( 'portalcategory' );
				$query = "SELECT * FROM #__focus_keywords " . $wheresqlstr . " ORDER BY " . $order . " LIMIT " . $start . "," . $perpage;
				$query = DB::query ( $query );
				while ( $item = DB::fetch_array ( $query ) ) {
						$vv = 'readtime';
						$v2 = 'catname';
						$v1 = 'catid';
						if ($item [$vv]) {
							$item [$vv] = date ( "Y-m-d H:i", $item [$vv] );
						} else {
							$item [$vv] = '<span class="error">未更新</span>';
						}
						$item [$v2] = '';
						if ($_G['cache']['portalcategory'] [$item [$v1]]) {
							$item [$v2] = '<input type="hidden" name="' . $v1 . '_old[' . $item ['id'] . ']" value="' . $item [$v1] . '">';
						}
						$item [$v2] .= html::select ( $v1 . '[' . $item ['id'] . ']', $catlist [$v], $item [$v1] );

					$item ['dateline'] = date ( "Y-m-d H:i", $item ['dateline'] );
					$listarr [] = $item;
				}
				$multipage = multi ( $listcount, $perpage, $_GET ['page'], $theurl . $urlplus );
			}
			$this->display ( 'focus' );
		}
	}

	/**
	 * 采集设置
	 *
	 */
	function onsetting() {
		global $_G;
		$navtitle = 'Automatic Import settings';
		if (submitcheck ( 'savesubmit' )) {
			//开始保存
			$va = array ('authorid', 'density', 'len_min', 'len_max', 'cn_min', 'en_min', 'number', 'saveimg' );
			$config = array ();
			foreach ( $va as $v ) {
				$config [$v] = intval ( $_POST [$v] );
			}
			$config ['author'] = daddslashes ( trim ( $_POST ['author'] ) );
			if (! $config ['len_min'])
				$config ['len_min'] = 1;
			if ($config ['len_max'] > 80 || $config ['len_max'] < $config ['len_min'])
				$config ['len_max'] = 80;
			if ($config ['density'] < 0 || $config ['density'] > 99)
				$config ['density'] = 0;
			$value = serialize ( $config );
			DB::query ( "REPLACE INTO #__common_setting (skey, svalue) VALUES ('importconfig','$value');" );
			require_once libfile ( 'function/cache' );
			updatecache ( 'setting' );
			showmessage ( "Automatic Import settings have been saved!", 'index.php?option=focus&task=setting' );
		} else {
			$sql = "select svalue from #__common_setting where skey='importconfig'";
			$importconfig = DB::result_first ( $sql );
			$importconfig = unserialize ( $importconfig );
			extract ( $importconfig );
			include template ( 'focus/setting' );
		}
	}

	/**
	 * 更新关键字
	 *
	 */
	function onupdate() {
		global $_G;
		$navtitle = lang ( 'focus', 'Update keyword' );
		$id = intval ( $_GET ['id'] );
		$ids = $_GET ['ids'];
		$this->load ( 'class/focus' );
		$this->load ('class/chinese');
		$_G['ch'] = new Chinese(CHARSET, 'PINYIN');
		$bi = new focus ( );
		$mtime = explode ( " ", microtime () );
		$starttime = $mtime [1] + $mtime [0];
		loadcache ( 'engine', 1 );
		$bi->read ( $id, '', 1 );
		if (is_array ( $bi->errorstr ))
			$status = $bi->errorstr;

		foreach ( $status as $v ) {
			$html .= $v . "<br>";
		}
		if ($bi->state) {
			foreach ( $bi->state as $v ) {
				$html .= $v . '<br>';
			}
		}
		$mtime = explode ( " ", microtime () );
		$time = $mtime [1] + $mtime [0] - $starttime;
		$html .= number_format ( $time, 4 ) . "秒";
		$this->showhtml ( $html );
	}

	/**
	 * 采集正文中的图片
	 *
	 */
	function onimg() {
		global $_G;
		$data = trim ( $_G ['gp_data'] );
		$picfile = '';
		if (empty ( $data )) {
			getpic ();
		}
		$_data = urlencode ( $data );
		$url = 'index.php?option=focus&task=img&data=' . $_data;
		$data = unserialize ( decompress ( $data ) );
		if (! is_array ( $data )) {
			getpic ();
		}
		if (! $data ['aid'] && $data ['itemid']) {
			$data ['aid'] = $data ['itemid'];
		}
		$pageorder = intval($data['pageorder']);
		if(!$pageorder) $pageorder=1;
		if (! isset ( $data ['url'] ) || ! isset ( $data ['aid'] )) {
			getpic ();
		}

		$itemid = intval ( $data ['aid'] );
		if (! $itemid) {
			getpic ();
		}
		$msgarr = DB::fetch_first ( 'SELECT * FROM #__portal_article_title WHERE aid=' . $data ['aid']);
		if (! $msgarr) {
			getpic ();
		}
		$sql = "SELECT content FROM #__portal_article_content WHERE aid='" . $data ['aid'] . "' AND pageorder='$pageorder'";
		$content = DB::result_first ( $sql );
		if (! $content) {
			getpic ();
		}
		//以下的所有exit都需要替换掉原文中的链接
		require_once libfile ( 'class/upload' );
		$upload = new cmsUpload ();
		$tmpfname = tempnam ( cmsFS::formatpath ( ROOT_PATH . "/data/tmp", false ), "FOO" );
		$ref = $data ['from'];
		$_G ['remote_ref'] = $ref;
		global $snoopy;
		if (! $snoopy) {
			require_once libfile ( 'class/snoopy' );
			$snoopy = new Snoopy ();
			$snoopy->rawheaders ["Pragma"] = "no-cache";
			$snoopy->maxredirs = 5;
			$snoopy->offsiteok = false;
			$snoopy->expandlinks = false;
		}
		if (! empty ( $ref )) {
			$snoopy->referer = $ref;
		}
		$data ['url'] = str_replace ( 'img.intozgc/', 'img.intozgc.com/', $data ['url'] );
		$xcontent = '';
		if ($snoopy->fetch ( $data ['url'] )) {
			$xcontent = $snoopy->results;
		} else {
			$xcontent = dfsockopen ( $data ['url']);
		}

		$strf = strtolower ( substr ( $xcontent, 0, 5 ) );
		//如果为空或者长度不足2K则返回空
		if (empty ( $xcontent ) or strlen ( $xcontent ) < 3096 or $strf == '<!doc' or $strf == '<html' or $strf == '<head') {
			@unlink ( $tmpfname );
			cutsrc ( $url, '', $content, '', $_data );
			getpic ();

		}
		if (! @$fp = fopen ( $tmpfname, 'wb' )) {
			cutsrc ( $url, '', $content, '', $_data );
			exit ( getpic () );
		} else {
			flock ( $fp, 2 );
			fwrite ( $fp, $xcontent );
			fclose ( $fp );
		}
		list ( $width, $height, $type, $attr ) = @getimagesize ( $tmpfname );
		switch ($type) {
			case IMG_GIF :
				$type = 'gif';
				break;
			case IMG_JPG :
				$type = 'jpg';
				break;
			case IMG_PNG :
				$type = 'png';
				break;
			default :
				$type = '';
				break;
		}
		if ($type) {
			$patharr ['ext'] = $type;
		} else {
			@unlink ( $tmpfname );
			cutsrc ( $url, '', $content, '', $_data );
			exit ( getpic () );
		}
		$temp = explode ( '/', $data ['url'] );

		$patharr ['name'] = md5 ( $data ['url'] ) . '.' . $type;
		$dirname = substr ( $patharr ['name'], 0, 2 ) . '/';
		$dirname .= substr ( $patharr ['name'], 2, 2 ) . '/';
		$dirname .= substr ( $patharr ['name'], 4, 2 ) . '/';
		$patharr ['ext'] = $upload->fileext ( $patharr ['name'] );

		$patharr ['isimage'] = $upload->is_image_ext ( $patharr ['ext'] );
		$patharr ['extension'] = $upload->get_target_extension ( $patharr ['ext'] );
		$patharr ['attachdir'] = $dirname;
		$patharr ['attachment'] = $patharr ['attachdir'] . $patharr ['name'];
		$patharr ['target'] = cmsFS::formatpath ( getglobal ( 'setting/attachdir' ) . './portal/' . $patharr ['attachment'], false );
		cmsFS::autocreatepath ( dirname ( $patharr ['target'] ) );
		if (file_exists ( $patharr ['target'] )) {
			$patharr ['isnew'] = false;
		} else {
			$patharr ['isnew'] = true;
			cmsFS::copy ( $tmpfname, $patharr ['target'] );
			@unlink ( $tmpfname );
			require_once libfile ( 'class/image' );
			$image = new image ();
			$image->Watermark ( $patharr ['target'], '', 'portal' );
			$patharr ['thumb'] = $image->Thumb ( $patharr ['target'], '', $_G ['setting'] ['thumbwidth'], $_G ['setting'] ['thumbheight'] );
		}
		@unlink ( $tmpfname );

		$patharr ['size'] = filesize ( $patharr ['target'] );
		if ($patharr ['size'] < 3096) {
			@unlink ( $patharr ['target'] );
			@unlink ( $patharr ['target'] . '.thumb.jpg' );
			unset ( $patharr );
		}
		$upmsg = false;
		if ($patharr ['size'] && $patharr ['target']) {
			if (! $msgarr ['pic']) {
				$umsgarr ['pic'] = $patharr ['attachment'];
				$upmsg = true;
			}
			if (! $msgarr ['summary']) {
				$umsgarr ['summary'] = getstr ( clearhtml ( strip_tags($content )), 150 );
				$upmsg = true;
			}
			$subject = strtolower ( trim ( substr ( $patharr ['name'], 0, strrpos ( $patharr ['name'], "." ) ) ) );
			if ($patharr ['isnew']) {
				$adata = array ("uid" => $msgarr ['uid'], "dateline" => TIMESTAMP, "aid" => $msgarr ['aid'], "filename" => daddslashes ( $patharr ['name'] ), "filetype" => $patharr ['extension'], "isimage" => $patharr ['isimage'], "filesize" => $patharr ['size'], "attachment" => $patharr ['attachment'], "thumb" => $patharr ['thumb'] );
				$aid = DB::Insert ( 'common_attachment', $adata, 1 );
			}
			if (! empty ( $patharr ['target'] )) {
				if ($patharr ['thumb']) {
					$pf = 'data/attachment/portal/' . $patharr ['attachment'] . '.thumb.jpg';
				} else {
					$pf = 'data/attachment/portal/' . $patharr ['attachment'];
				}
				$bigurl = $_G ['siteurl'] . 'data/attachment/portal/' . $patharr ['attachment'];
				$picfile = ROOT_PATH . "/" . $pf;
				$picurl = $_G ['siteurl'] . $pf;
				if ($bigurl == $picurl) {
					$rf = '<img src="' . $picurl . '">';
				} else {
					$rf = '<a href="' . $bigurl . '" target=_blank><img src="' . $picurl . '"></a>';
				}
				cutsrc ( $url, $rf, $content, $picurl, $_data );
			}
			if ($upmsg) {
				DB::Update ( 'portal_article_title', $umsgarr, 'aid=' . $msgarr ['aid'] );
			}
		} else {
			cutsrc ( $url, '', $content, '', $_data );
		}
		exit ( getpic ( $picfile ) );
	}
	function showhtml($html) {
		global $_G;
		include template ( 'common/header' );
		include template ( 'focus/header' );
		echo $html;
		include template ( 'focus/footer' );
		include template ( 'common/footer' );
	}
}

function getpic($fn = '') {
	if (! $fn)
		$fn = ROOT_PATH . '/static/image/common/none.gif';
	list ( $width, $height, $type, $attr, $ww ) = @getimagesize ( $fn );
	switch ($type) {
		case IMG_GIF :
			$type = 'gif';
			break;
		case IMG_JPG :
			$type = 'jpeg';
			break;
		case IMG_PNG :
			$type = 'png';
			break;
		default :
			$type = '';
			break;
	}
	$fn = cmsFS::formatpath($fn, false);
	if ($type) header ( "Content-type: image/$type" );
    readfile($fn);
    exit;
}

function cutsrc($url, $rf, $content, $pic = '', $data = '') {
	global $_G;
	$_data = unserialize ( decompress ( urldecode($data ) ));
	$content = str_replace ( "\\'", "'", $content );
	//$content = str_replace ( "'", "\\'", $content );
	$content = str_replace ( "##'##", "'", $content );
	$url = 'index.php?option=focus&amp;task=img&amp;data='.$data;
	$content = str_ireplace ( '<img src=' . $url . '>', $rf, $content );
	$content = str_ireplace ( '<img src="' . $url . '">', $rf, $content );
	$content = str_ireplace ( '<img src=\\"' . $url . '\\">', $rf, $content );

	if(strpos($content, $url)){
		$content = str_replace($url, $pic, $content);
	} else {
		$url = 'index.php?option=focus&task=img&data='.$data;
		$content = str_ireplace ( '<img src=' . $url . '>', $rf, $content );
		$content = str_ireplace ( '<img src="' . $url . '">', $rf, $content );
		$content = str_ireplace ( '<img src=\\"' . $url . '\\">', $rf, $content );
		if(strpos($content, $url)){
			$content = str_replace($url, $pic, $content);
		}
	}
	$content = daddslashes ( $content );
	$aid = $_data['aid'];
	$pageorder = intval($_data['pageorder']);
	DB::Update ( 'portal_article_content', array ('content' => $content ), array('aid'=>$aid, 'pageorder'=>$pageorder) );
}